<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\controller\android\v10;


use app\api\model\Aliyunoss;
use app\api\model\PollingModel;
use app\index\model\Pdf;
use Doctrine\ORM\Version;
use think\Config;
use think\Controller;

use app\api\model\Authority;
use app\api\model\Common;
use  app\api\model\OrderModel;
use think\Db;
use think\Request;

class Visa extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;

    public function _initialize()
    {

        $this->model = new Authority();

        $this->us = Authority::check(1);

    }

    public function Applets()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            db('visa_form')->insertGetId([
                'visa_map' => '',
                'creation_time' => time(),
                'capital_id' => '',
                'autograph' => '',
                'order_id' => $data['order_id'],
                'title' => '增项减项签证单',
            ]);
        }

        r_date([], 200, '新增成功');
    }

    public function SignUp()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $pdf = (new Pdf())->shi($data['order_id']);
            if ($pdf) {
                $textDefault  = [];
                $background   = ROOT_PATHS . '/uploads/PDF/' . $data['order_id'] . '.png';//背景
                $img          = imagecreatefrompng($background);
                $img_info     = imagesy($img);
                $imageDefault = [
                    'left' => 120,
                    'top' => $img_info - 170,
                    'right' => 0,
                    'bottom' => 0,
                    'width' => 100,
                    'height' => 100,
                    'opacity' => 50,
                ];
                if (file_exists($background)) {
                    if (!empty($data['autograph']) && (parse_url($data['autograph'])['host'] == 'imgaes.yiniaoweb.com' || parse_url($data['autograph'])['host'] == 'api.yiniaoweb.com')) {
                        $path = '/app/' . (new PollingModel())->file_exists_S3($data['autograph'], ROOT_PATH . 'public/app/');
                    } else {
                        $path = parse_url($data['autograph'], PHP_URL_PATH);

                    }
                    $config['image'][]['url'] = ROOT_PATHS . $path;
                    $filename                 = ROOT_PATHS . '/ContractNumber/' . $data['order_id'] . '.jpg';
                    Common::getbgqrcode($imageDefault, $textDefault, $background, $filename, $config);

                    $ali = new Aliyunoss();
                    if (file_exists($filename)) {
                        $oss_result = $ali->upload('contract/' . config('city') . '/' . $data['order_id'] . time() . '.jpg', $filename);
                        if ($oss_result['info']['http_code'] == 200) {
                            $path = parse_url($oss_result['info']['url'])['path'];
                            if (empty($data['id'])) {
                                db('visa_form')->insertGetId([
                                    'visa_map' => 'https://images.yiniao.co' . $path,
                                    'creation_time' => time(),
                                    'signing_time' => time(),
                                    'capital_id' => implode(',', $pdf['capital_id']),
                                    'autograph' => $data['autograph'],
                                    'order_id' => $data['order_id'],
                                    'title' => '增项减项签证单',
                                ]);
                            } else {
                                db('visa_form')->where('id', $data['id'])->update([
                                    'visa_map' => 'https://images.yiniao.co' . $path,
                                    'capital_id' => implode(',', $pdf['capital_id']),
                                    'autograph' => $data['autograph'],
                                    'signing_time' => time(),
                                ]);
                            }

                            db('capital')->whereIn('capital_id', $pdf['capital_id'])->update([
                                'signed' => 1,
                            ]);

                            if (file_exists($filename)) {
                                unlink($filename);
                            };
                            if (file_exists($config['image'][0]['url'])) {
                                unlink($config['image'][0]['url']);
                            }


                        }
                    }
                    db()->commit();
                    r_date([], 200, '新增成功');
                }
            }

        } catch (\Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /*
     * 列表
     */
    public function VisaList()
    {
        $data      = Request::instance()->post();
        $visa_form = db('visa_form')->where('order_id', $data['order_id'])->field('id,title,signing_time,capital_id,visa_map')->select();
        foreach ($visa_form as $k => $o) {
            $capital = db('capital')->where('capital.enable', 1)->whereIn('capital_id', $o['capital_id'])->select();
            $money   = 0;
            foreach ($capital as $item) {
                $capital = Db::query("select * from visa_form where FIND_IN_SET('" . $item['capital_id'] . "',capital_id) ");
                if (!empty($o['signing_time']) && $item['increment'] == 1 && $o['signing_time'] < $item['untime']) {
                    $money += $item['to_price'];
                }
                if ($item['types'] == 2 && $item['increment'] != 1) {
                    $money -= $item['to_price'];
                }
                if (!empty($o['signing_time']) && $item['increment'] == 1 && $o['signing_time'] > $item['untime'] && count($capital) > 1) {
                    $money -= $item['to_price'];
                }
                if ($item['increment'] == 1 && $item['types'] == 1) {
                    $money += $item['to_price'];
                }

            }

            $visa_form[$k]['creation_time'] = empty($o['signing_time']) ? '' : date('Y-m-d H:i:s', $o['signing_time']);
            $visa_form[$k]['money']         = $money;

        }

        r_date($visa_form, 200);
    }

    /*
     * 列表
     */
    public function VisaInfo()
    {
        $data = Request::instance()->post();
//        $visa_form=db('visa_form')->where('id', $data['id'])->column('capital_id');
        if (empty($data['id'])) {
            $data = db('capital')
                ->join('contract', 'contract.orders_id=capital.ordesr_id', 'left')
                ->where('IF(capital.untime !=0,capital.untime>contract.con_time,capital.untime<contract.con_time)')
                ->where('capital.enable', 1)
                ->where('capital.ordesr_id', $data['order_id'])->where(function ($query) {
                    $query->where('capital.types=2')->whereOr('capital.increment=1');
                })->where('signed', 0)
                ->field('capital.projectId,capital.capital_id,capital.class_a,capital.class_b,capital.company,capital.square,capital.un_Price,capital.zhi,capital.to_price,capital.fen,capital.increment,capital.types,capital.agency,capital.signed,capital.cooperation')->select();
        } else {
            $visa_form = db('visa_form')->where('id', $data['id'])->column('capital_id');

            if (empty($visa_form)) {
                $data = db('capital')
                    ->join('contract', 'contract.orders_id=capital.ordesr_id', 'left')
                    ->where('capital.ordesr_id', $data['order_id'])
                    ->where('capital.enable', 1)
                    ->where('IF(capital.untime !=0,capital.untime>contract.con_time,capital.untime<contract.con_time)')
                    ->where(function ($query) {
                        $query->where('capital.types=2')->whereOr('capital.increment=1');
                    })->where('capital.signed', 0)
                    ->field('capital.projectId,capital.capital_id,capital.class_a,capital.class_b,capital.company,capital.square,capital.un_Price,capital.zhi,capital.to_price,capital.fen,capital.increment,capital.types,capital.agency,capital.signed,capital.cooperation')->select();
            } else {

                $data = db('capital')->whereIn('capital_id', $visa_form)
                    ->where('capital.enable', 1)
                    ->where(function ($query) {
                        $query->where('types=2')->whereOr('increment=1');
                    })->where('signed', 0)
                    ->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,types,agency,signed,cooperation')->select();
            }


        }

        if (!empty($data)) {
            foreach ($data as $k => $item) {

//                $capital=Db::query("select * from visa_form where FIND_IN_SET('".$item['capital_id']."',capital_id) ");
                ;

                if ($item['increment'] == 1) {

                    $data[$k]['money'] = 1;
                }
                if ($item['types'] == 2) {
                    $data[$k]['money'] = 2;
                }
                if ($item['types'] == 2 && $item['increment'] != 1) {
                    $data[$k]['money'] = 2;
                }
                if ($item['types'] == 1 && $item['increment'] == 1) {
                    $data[$k]['money'] = 1;
                }

                if ($item['types'] == 2 && $item['increment'] == 1) {
                    $data[$k]['money'] = 3;
                }

                $data[$k]['un_Price'] = round($item['un_Price'],2);
                $data[$k]['to_price'] = round($item['to_price'],2);
            }
        }
        # 按money升序排序
        $b = $this->arraySort($data, 'types', SORT_DESC);

        r_date($b, 200);
    }

    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }

}
        
        

    

